package rs.udd.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import rs.udd.exceptions.UddException;
import rs.udd.model.Category;
import rs.udd.service.CategoryService;
import rs.udd.service.document.indexer.handler.PDFHandler;

@Controller
@RequestMapping({ "categories", "/categories", "/categories/" })
public class CategoryController {

	private static final Logger LOGGER = LogManager.getLogger(CategoryController.class);
	
	@Autowired
	private CategoryService categoryService;
	
//	@RequestMapping(value = "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//	public @ResponseBody List<Category> getAllCategories(@RequestParam("term") String term) throws UddException {
//		LOGGER.info("Fetching category for " + term);
//		List<Category> categories = categoryService.findCategoryByNameLike(term);
//		LOGGER.info("categories size: " + categories.size());
//		return categories;
//	}
	
	@RequestMapping(value = "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody List<String> getAllCategories(@RequestParam("term") String term) throws UddException {
		
		String result[] = term.trim().split(PDFHandler.META_DATA_SEPARATOR);
		String lastCategoryName = result[result.length-1].trim();
		
		List<Category> categories = categoryService.findCategoryByNameLike(lastCategoryName);
		List<String> categoryNames = new ArrayList<String>(categories.size());
		for (Category category : categories) {
			categoryNames.add(category.getName());
		}
		return categoryNames;
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody String add(String newCategoryName) throws UddException {
		
		String retVal = "Category '" + newCategoryName + "' successfully added.";
		
		Category newCategory = categoryService.add(newCategoryName);
		if (newCategory == null) {
			retVal = "Category '" + newCategoryName + "' already exists.";
		}
		
		LOGGER.info(retVal);
		return retVal;
	}
	
}
